package com.climber.android.commonres.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.view.View
import androidx.lifecycle.Lifecycle
import com.climber.android.commonres.R
import com.climber.android.commonsdk.util.WechatImagePicker
import com.qingmei2.rximagepicker.core.RxImagePicker
import com.qingmei2.rximagepicker_extension.MimeType
import com.qingmei2.rximagepicker_extension_wechat.WechatConfigrationBuilder
import io.ganguo.library.mvp.ui.mvp.IPresenter
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.ganguo.library.mvp.util.FileUtils
import io.ganguo.library.mvp.util.RxLifecycleUtils
import io.ganguo.library.mvp.util.StatusBarUtils
import io.ganguo.library.mvp.util.ToastHelper
import io.library.android.zxing.QRCodeUtils
import io.library.android.zxing.ui.QRCodeFragment

/**
 * Created by Mikes at 2020-04-10 16:38
 */
class AppQRScanActivity : BaseMVPActivity<IPresenter>(){
    private val imagePicker : WechatImagePicker by lazy {
        RxImagePicker.create<WechatImagePicker>(WechatImagePicker::class.java)
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
    }

    override fun initView() {
        StatusBarUtils.setTranslucentImage(this)
    }

    override fun initListener() {
        getSmartToolBar()?.setRightViewClickListener(View.OnClickListener {
            requestSinglePermission(Manifest.permission.READ_EXTERNAL_STORAGE, "") { storageAllowed ->
                if (storageAllowed) {
                    pickImageToScan()
                }
            }
        })
    }

    override fun getLayoutResourceId(): Int  = R.layout.com_activity_qr_scan

    override fun initData() {
        requestSinglePermission(Manifest.permission.CAMERA, "") { cameraAllowed ->
            if (cameraAllowed) {
                showQRScanView()
            }
        }
    }

    private fun showQRScanView(){
        val qrCodeFragment = QRCodeFragment()

        qrCodeFragment.analyzeCallback = object : QRCodeUtils.AnalyzeCallback{
            override fun onAnalyzeSuccess(bitmap: Bitmap?, result: String) {
                setResult(Activity.RESULT_OK, Intent().putExtra("result", result))
                finish()
            }

            override fun onAnalyzeFailed() {
                ToastHelper.toastMessage("识别失败，请重新识别。")
            }
        }

        with(supportFragmentManager.beginTransaction()) {
            this.add(R.id.qrScanLayout, qrCodeFragment)
            this.commit()
        }
    }

    private fun pickImageToScan(){
        imagePicker.openGallery(
                this,
                WechatConfigrationBuilder(getSupportMimeType(), false)
                        .showSingleMediaType(true)
                        .capture(false)
                        .maxSelectable(1)
                        .spanCount(4)
                        .countable(false)
                        .build()
        )
                .`as`(RxLifecycleUtils.bindUntilEvent(this, Lifecycle.Event.ON_DESTROY))
                .subscribe { result ->
                    val filePath = FileUtils.getPath(this, result.uri)
                            ?: return@subscribe

                    val qrCodeResult = QRCodeUtils.decodeQRCode(filePath)
                    setResult(Activity.RESULT_OK, Intent().putExtra("result", qrCodeResult))
                    finish()
                }
    }

    private fun getSupportMimeType() : Set<MimeType> = setOf(MimeType.JPEG, MimeType.PNG, MimeType.BMP)
}